import { Component } from '@angular/core';
// aws-sdk引用 使用js直接传到s3上面
import * as AWS from 'aws-sdk/global';
import * as S3 from "aws-sdk/clients/s3";
import { GetDataService } from './core/get-data.service';

@Component({
  selector: 'mce-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  constructor(
    private service: GetDataService
  ) {
    // 手动加cookie 上线需要注释 本地测试使用
    var date=new Date();
    date.setTime(date.getTime()+3000*60*1000); //设置date为当前时间+30分
    document.cookie="iApproveXProtect=xj8w9kp8r0rbzmk5rvejsw0duapckgv6; expires="+date.toUTCString();
  }
  title = 'webTinyMCE';
  // 初始化
  tinyMenu = {
    plugins: [
      'advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker',
      'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
      'table emoticons template paste help'
    ],
    toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify |' +
      ' bullist numlist outdent indent | link image | print preview media fullpage fullscreen |' +
      'forecolor backcolor emoticons | help',
    menu: {
      favs: {title: 'My Favorites', items: 'code visualaid | searchreplace | spellchecker | emoticons'}
    },
    menubar: 'favs file edit view insert format tools table help',
    content_css: 'css/content.css',
    images_upload_handler: (blobInfo, success, failure)=>{
      console.log(blobInfo);
      let file = {value: blobInfo.blob(), name: blobInfo.filename()}
      this.getPreVoucher(file, success);
    }
  };
  // 获取 aws 凭证
  getPreVoucher(file, success) {
    // 定义文件数据
    try {
      this.service.getPreVoucher().subscribe((res: any) => {
        this.uploadFile(file, success, res);
      }, () => {
        // this.common.createMessage('failed', 'close');
      });
    } catch (error) {
      // this.common.createMessage('failed', 'close');
    }
  }
  // 上传文件
  uploadFile(file, success, obj) {
    AWS.config.update({
      // 地区不同 region 不同
      region: 'cn-north-1',
      credentials: new AWS.CognitoIdentityCredentials({
        IdentityPoolId: obj.identity_pool_id,
        IdentityId: obj.identity_id,
        Logins: {
          'cognito-identity.cn-north-1.amazonaws.com.cn': obj.token
        }
      })
    });
    // var keyStream = s3Files.connect({
    //   region: 'cn-north-1',
    //   bucket: 'iapprove-storages-dev'
    // }).createKeyStream('/media/DataReactor/ImportEntry/SourceFile', [file.value])
    // // Stream the files.
    // s3Files.createFileStream(keyStream).on('data', function (chunk) {
    //   console.log(chunk.path, chunk.data.length)
    // })
    // Create S3 service object
    let s3 = new S3({apiVersion: '2006-03-01',params: {Bucket: 'iapprove-storages-dev'}});
    const params = {
      Bucket: 'iapprove-storages-dev'+'/media/DataReactor/ImportEntry/SourceFile',
      Key: (new Date()).getTime()+file.name,
      Body: file.value,
      ContentType: 'image/jpeg'
    };
    s3.upload(params, (err, data) => {
      if(err) {
        console.log(err);
        return false;
      }
      console.log(data);
      // 返回图片路径有问题无法预览
      success(data.Location)
      // this.createTask(values, data.Key.substring(6));
    }).on('httpUploadProgress', (e:any)=>{
      let precent: any = parseInt(e.loaded, 10)/parseInt(e.total, 10);
      console.log(precent);
    });
  }
}
